<template>
	<el-dialog :title="form.id ? '修改证书模版' : '新增证书模版'" v-model="visible" :close-on-click-modal="false" draggable>
		<div style="display: flex;align-items: center;position: relative;height: 100%">
			<el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
				<el-form-item label="证书名称" prop="certificateTemplateName">
					<el-input v-model="form.certificateTemplateName" placeholder="请选择证书名称" />
				</el-form-item>
				<el-form-item label="证书类型" prop="certificateType">
					<el-select @change="typechange" filterable v-model="form.certificateTypes" placeholder="请选择证书类型">
						<el-option :label="item.label" :value="item.value" v-for="(item, index) in certificate_type" :key="index"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="证书性质" prop="certificateNature">
					<el-select @change="naturechange" filterable v-model="form.certificateNatures" placeholder="请选择证书性质">
						<el-option :label="item.label" :value="item.value" v-for="(item, index) in certificate_nature" :key="index"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item filterable label="颁发机构" prop="authority">
					<el-select @change="authchange" filterable v-model="form.authoritys" placeholder="请选择颁发机构">
						<el-option :label="item.label" :value="item.value" v-for="(item, index) in certification_authority" :key="index"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item class="mr0" style="display: flex;flex-direction: column">
					<el-row :span="4" class="mb20">
						<el-form-item label="永久有效" prop="isPermanent" required>
							<el-switch v-model="form.isPermanents" @change="switchChange" />
						</el-form-item>
					</el-row>
           <el-row  v-if="isopend">
             <el-row :span="4" class="mb20">
               <el-form-item label="时间有效期" prop="time_valid">
                 <el-switch v-model="form.time_valids" @change="switchChangetime"></el-switch>
               </el-form-item>
             </el-row>
             <el-row v-if="isopendtime">
               <el-col :span="12" class="mb20">
                 <el-form-item label=" " prop="startTime">
                   <el-date-picker
                       format="YYYY/MM/DD"
                       value-format="YYYY-MM-DD"
                       @change="startchange"
                       v-model="form.startTime"
                       type="date"
                       label="Pick a date"
                       placeholder="有效期开始时间"
                       style="width: 100%"
                       :disabled="istimeswitch"
                   />
                 </el-form-item>
               </el-col>
               <el-col :span="12" class="mb20">
                 <el-form-item label=" " prop="endTime">
                   <el-date-picker
                       format="YYYY/MM/DD"
                       v-model="form.endTime"
                       value-format="YYYY-MM-DD"
                       type="date"
                       @change="endTimechange"
                       label="Pick a date"
                       placeholder="有效期结束时间"
                       style="width: 100%"
                       :disabled="istimeswitch"
                   />
                 </el-form-item>
               </el-col>
             </el-row>
             <el-row v-if="isopendtime === false">
               <el-col>
                 <div style="display: flex">
                   <el-input-number :min="1" style="margin-left: 40px;width: 100px; text-align: center" v-model="form.effectiveYear" placeholder="请输入有效年限"></el-input-number>
                   <div style="margin-left: 10px">年</div>
                 </div>
               </el-col>
             </el-row>
           </el-row>
				</el-form-item>
				<el-form-item style="display: flex;flex-direction: column" prop="fileModule">
					<div style="display: flex;">
            <el-upload
                ref="uploadppt"
                limit="1"
                accept=".pptx"
                class="upload-demo"
                :action="actionUrl + '/uploadFile'"
                :on-success="uploadSuccess"
                style="width: 600px"
                :before-remove="removeFile(0)"
                :before-upload="uploadbefore"
            >
              <el-button plane>
                <!--							<el-icon><Download /></el-icon>-->
                <svg t="1712807276206" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1192" width="200" height="200"><path d="M659.626667 780.8h-298.666667c-104.106667 0-189.44-85.333333-189.44-189.44 0-91.306667 63.146667-167.253333 150.186667-185.173333 9.386667-95.573333 90.453333-170.666667 188.586666-170.666667s179.2 75.093333 188.586667 170.666667c87.04 17.92 150.186667 93.866667 150.186667 185.173333 0 104.106667-85.333333 189.44-189.44 189.44zM510.293333 286.72c-75.946667 0-138.24 62.293333-138.24 138.24v26.453333l-23.04 1.706667c-71.68 5.973333-126.293333 65.706667-126.293333 137.386667 0 75.946667 62.293333 138.24 138.24 138.24h298.666667c75.946667 0 138.24-62.293333 138.24-138.24 0-72.533333-53.76-131.413333-126.293334-137.386667l-23.04-1.706667v-26.453333c0-76.8-62.293333-138.24-138.24-138.24z" fill="#190D04" p-id="1193"></path><path d="M584.533333 550.4c-7.68 0-14.506667-3.413333-19.626666-9.386667l-45.226667-56.32c-2.56-2.56-5.12-3.413333-5.973333-3.413333-1.706667 0-4.266667 0-6.826667 2.56l-52.053333 57.173333c-9.386667 10.24-25.6 11.093333-35.84 1.706667s-11.093333-25.6-1.706667-35.84l52.053333-57.173333c11.946667-12.8 28.16-19.626667 46.08-19.626667 17.066667 0.853333 34.133333 8.533333 44.373334 22.186667l45.226666 56.32c8.533333 11.093333 7.68 27.306667-3.413333 35.84-5.12 4.266667-11.093333 5.973333-17.066667 5.973333z" fill="#E56D1C" p-id="1194"></path><path d="M510.293333 651.946667c-14.506667 0-25.6-11.093333-25.6-25.6V459.946667c0-14.506667 11.093333-25.6 25.6-25.6s25.6 11.093333 25.6 25.6v167.253333c0 13.653333-11.946667 24.746667-25.6 24.746667z" fill="#E56D1C" p-id="1195"></path></svg>上传正面模版
              </el-button>
              <div class="el-upload__tip" style="margin-left: 15px"><i style="color: red;margin-right: 10px">*</i>支持扩展名：.pptx 且不超过3MB</div>
            </el-upload>
            <div v-if="isdownload" style="width: 50%;">
              <span style="padding-right: 15px; ">{{templateName}}</span>
<!--              <el-button @click="preview">模版预览</el-button>-->
              <el-button @click="downloadTemplate">模版下载</el-button>
            </div>
          </div>
				</el-form-item>
				<el-form-item>
					<el-upload
							ref="uploadpng"
							limit="1"
							accept=".png"
							class="upload-demo"
							:action="actionUrl + '/uploadFile'"
							:on-success="uploadSuccessicon"
              :before-upload="uploadbeforeicon"
              :before-remove="removeFile(1)"
							style="width: 600px"
					>
						<el-button plane>
              <svg t="1712807276206" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1192" width="200" height="200"><path d="M659.626667 780.8h-298.666667c-104.106667 0-189.44-85.333333-189.44-189.44 0-91.306667 63.146667-167.253333 150.186667-185.173333 9.386667-95.573333 90.453333-170.666667 188.586666-170.666667s179.2 75.093333 188.586667 170.666667c87.04 17.92 150.186667 93.866667 150.186667 185.173333 0 104.106667-85.333333 189.44-189.44 189.44zM510.293333 286.72c-75.946667 0-138.24 62.293333-138.24 138.24v26.453333l-23.04 1.706667c-71.68 5.973333-126.293333 65.706667-126.293333 137.386667 0 75.946667 62.293333 138.24 138.24 138.24h298.666667c75.946667 0 138.24-62.293333 138.24-138.24 0-72.533333-53.76-131.413333-126.293334-137.386667l-23.04-1.706667v-26.453333c0-76.8-62.293333-138.24-138.24-138.24z" fill="#190D04" p-id="1193"></path><path d="M584.533333 550.4c-7.68 0-14.506667-3.413333-19.626666-9.386667l-45.226667-56.32c-2.56-2.56-5.12-3.413333-5.973333-3.413333-1.706667 0-4.266667 0-6.826667 2.56l-52.053333 57.173333c-9.386667 10.24-25.6 11.093333-35.84 1.706667s-11.093333-25.6-1.706667-35.84l52.053333-57.173333c11.946667-12.8 28.16-19.626667 46.08-19.626667 17.066667 0.853333 34.133333 8.533333 44.373334 22.186667l45.226666 56.32c8.533333 11.093333 7.68 27.306667-3.413333 35.84-5.12 4.266667-11.093333 5.973333-17.066667 5.973333z" fill="#E56D1C" p-id="1194"></path><path d="M510.293333 651.946667c-14.506667 0-25.6-11.093333-25.6-25.6V459.946667c0-14.506667 11.093333-25.6 25.6-25.6s25.6 11.093333 25.6 25.6v167.253333c0 13.653333-11.946667 24.746667-25.6 24.746667z" fill="#E56D1C" p-id="1195"></path></svg>上传图标
						</el-button>
						<div class="el-upload__tip" style="margin-left: 15px">支持扩展名：.png 且不超过200kb</div>
					</el-upload>
				</el-form-item>
			</el-form>
		</div>
		<template #footer>
			<span class="dialog-footer">
				<!--				<el-button @click="visible = false">取消</el-button>-->
				<el-button type="primary" @click="onSubmit" :disabled="loading" style="width: 150px; height: 40px">提交</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="ZsglCertificateTemplateDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage } from '/@/hooks/message';
import { getObj, addObj, putObj } from '/@/api/train/zsglCertificateTemplate';
import type { UploadProps, UploadUserFile } from 'element-plus';
import { rule } from '/@/utils/validate';
// import file from '/@/components/Material/file.vue';
import { office,officeView} from '/@/api/train/kszlFile';
const emit = defineEmits(['refresh','refreshName']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
// 上传ref
const uploadppt = ref<UploadInstance>()
const uploadpng = ref<UploadInstance>();
// 时间禁用开关
const istimeswitch = ref(false);
// 下载模版开关
const isdownload = ref(false)

// 上传模版提交

// 控制时间有效期的开关
const isopendtime = ref(true)

// 控制时间隐藏开关
const isopend = ref(true)
// 定义字典
const { certification_authority, certificate_nature, yes_no_type, certificate_type } = useDict(
	'certification_authority',
	'certificate_nature',
	'yes_no_type',
	'certificate_type'
);


onMounted(() => {
	office().then((res) => {
		actionUrl.value = res.data;
	});
	officeView().then(res =>  {
		actionUrl1.value = res.data
	})
});

// 类型改变
const typechange = (val : any) => {
	console.log(val)
	console.log(certificate_type.value[val].label)
}


const authchange = (val : any) => {
	console.log(certification_authority.value[val].label)
}
// 有效期判定时间
const switchChange = () => {
  if (form.isPermanents) {
    isopend.value = false
    form.isPermanent = 1;
    istimeswitch.value = true;
    form.startTime = '2000-12-12';
    form.endTime = '2099-12-12';
    return;
  }
  isopend.value = true
  istimeswitch.value = false;
  form.startTime = '';
  form.endTime = '';
  form.isPermanent = 0;
};
// 有效期时间控制改变
const switchChangetime = () => {
  if(!form.time_valids){
    form.timeValid = 0
    isopendtime.value = false
  } else {
    form.timeValid = 1
    isopendtime.value = true
  }
}

// 存储文件大小
const filesize:number = ref()
// 获取模版名称
const templateName = ref()
// 后台请求路径
const actionUrl = ref();
// 文件预览路径
const actionUrl1 = ref()
// 上传文件列表
const filelist = ref<UploadUserFile[]>([
	{
		name: 'food.jpeg',
		url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
	},
]);
// 上传图标列表
const filelisticon = ref<UploadUserFile[]>([]);
// 提交表单数据
const form = reactive({
	id: '',
	certificateTemplateId: '',
	certificateTemplateName: '',
	certificateType: '',
	certificateNature: '',
	authority: '',
	isPermanent: 1,
	startTime: '',
	endTime: '',
	remark: '',
	fileName: '',
	fileNameAll: '',
	fileNameView: '',
	fileAddress: '',
	fileSize: '',
	filePage: '',
	fileUid: '',
	photoName: '',
	photoNameAll: '',
	photoNameView: '',
	photoAddress: '',
	photoSize: '',
	photoUid: '',
	createBy: '',
	createTime: '',
	updateBy: '',
	updateTime: '',
	isPermanents: true,
	certificateTypes: '',
	authoritys: '',
	certificateNatures: '',
  timeValid: 1,
  time_valids: true,
  effectiveYear : 1,
});

// 重置表单数据
const formreset = {
	certificateTemplateId: '',
	certificateTemplateName: '',
	certificateType: '',
	certificateNature: '',
	authority: '',
	isPermanent: 1,
	startTime: '',
	endTime: '',
	remark: '',
	fileName: '',
	fileNameAll: '',
	fileNameView: '',
	fileAddress: '',
	fileSize: '',
	filePage: '',
	fileUid: '',
	photoName: '',
	photoNameAll: '',
	photoNameView: '',
	photoAddress: '',
	photoSize: '',
	photoUid: '',
	createBy: '',
	createTime: '',
	updateBy: '',
	updateTime: '',
	isPermanents: true,
	certificateTypes: '',
	authoritys: '',
	certificateNatures: '',
  timeValid: 1,
  time_valids: true,
  effectiveYear : 1,
}



// 定义校验规则
const dataRules = reactive<FormRules<RuleForm>>({
	certificateTemplateName: [{ required: true, message: '请输入证书名称', trigger: 'blur' }],
	certificateType: [{required: true, message: '请选择证书类型', trigger: 'blur',},],
	certificateNature: [{ required: true, message: '请选择证书性质', trigger: 'blur' }],
	authority: [{ required: true, message: '请选择颁发机构', trigger: 'blur' }],
	startTime: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
	endTime: [{ required: true, message: '请选择结束时间', trigger: 'blur' }],
});

// 删除文件清空表单
const removeFile = (index:number) => {
  if(index == 0) {
    Object.assign(form,{
      fileName: '',
      fileNameAll: '',
      fileNameView: '',
      fileAddress: '',
      fileSize: '',
      filePage: '',
      fileUid: '',
    })
  }
  Object.assign(form,{
    photoName: '',
    photoNameAll: '',
    photoNameView: '',
    photoAddress: '',
    photoSize: '',
    photoUid: '',
  })
}

// 时间校验函数
const startchange = () => {
  if (form.startTime && from.endTime && from.startTime > from.endTime) {
    from.startTime = ''
    useMessage().error('开始时间不能大于结束时间')
  }
}
const endTimechange = () => {
  if(form.endTime && form.endTime < form.startTime) {
    form.endTime = ''
    useMessage().error('结束时间不能小于开始时间')
  }
}

// 上传成功后的form表单赋值 on-Success
const uploadSuccess = (val: any) => {
	console.log(val,1111111111111)
	form.fileName = val.data.suffix;
	form.fileNameAll = val.data.title;
	form.fileNameView = val.data.name;
	form.fileAddress = val.data.url;
	form.fileSize = val.data.size;
	form.fileUid = val.data.id;
};
const uploadSuccessicon = (val: any) => {
	form.photoName = val.data.suffix;
	form.photoNameAll = val.data.title;
	form.photoNameView = val.data.name;
	form.photoAddress = val.data.url;
	form.photoSize = val.data.size;
	form.photoUid = val.data.id;
};

// 打开弹窗
const openDialog = (id: string) => {
  isopend.value = false
  // form.isPermanents = true
	visible.value = true;
	form.id = '';
	isdownload.value = false
	istimeswitch.value = false
  isopendtime.value = true
	// 重置表单数据
	nextTick(() => {
		Object.assign(form , formreset)
	});
	// 获取zsglCertificateTemplate信息
	if (id) {
		form.id = id;
		// 判断状态 是否显示预览按钮
		isdownload.value = true
		getzsglCertificateTemplateData(id);
	}
};
//
// const handleChange = (file , fileList) => {
//
// }
// 提交
const onSubmit = async () => {
  if(form.fileSize || filenum.value){
    if(form.fileSize / 1024 / 1024 >= 3) {
      useMessage().error('文件大小不应该超过1M')
      uploadppt.value.clearFiles()
      form.fileSize = 0
      Object.assign(form,{
        fileName: '',
        fileNameAll: '',
        fileNameView: '',
        fileAddress: '',
        fileSize: '',
        filePage: '',
        fileUid: '',
      })
      return
    }
  } else {
    useMessage().error('请传入ppt模版')
    return
  }
  if(form.photoSize) {
    if(form.photoSize / 1024 /200 >=1) {
      useMessage().error('图片大小不应该超过200KB')
      uploadpng.value.clearFiles()
      Object.assign(form,{
        photoName: '',
        photoNameAll: '',
        photoNameView: '',
        photoAddress: '',
        photoSize: '',
        photoUid: '',
      })
      return
    }
  }
	form.authority = parseInt(form.authoritys);
	form.certificateNature = parseInt(form.certificateNatures);
	form.certificateType = parseInt(form.certificateTypes);
  form.effectiveYear = parseInt(form.effectiveYear)
  console.log(form)
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		loading.value = true;
		form.id ? await putObj(form) : await addObj(form);
		uploadppt.value.clearFiles()
		uploadpng.value.clearFiles()
		useMessage().success(form.id ? '修改成功' : '添加成功');
    filenum.value = 0
		visible.value = false;

		emit('refresh');
		emit('refreshName')
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};
// 模版地址链接
const templateId = ref()
// 预览链接地址
const allurl = ref()
// 模版下载
const downloadTemplate = () => {
	const baseUrl = '/downloadFile/'
	window.open(
			actionUrl.value + baseUrl + templateId.value
	)
}

// 模版预览
const preview = () => {
	window.open(allurl.value)
}

// 存储文件大小
const filenum = ref()

// 初始化表单数据
const getzsglCertificateTemplateData = (id: string) => {
	// 获取数据
	loading.value = true;
	getObj(id)
		.then((res: any) => {
      console.log(res.data.fileSize,11111111)
			Object.assign(form, res.data)
      filenum.value = res.data.fileSize
			form.certificateNatures = certificate_nature.value[form.certificateNature].label
			form.certificateTypes = certificate_type.value[form.certificateType].label
			form.authoritys = certification_authority.value[form.authority].label

			// 获取文件的唯一id
			templateId.value = form.fileUid
			// 获取文件名全称
			templateName.value = form.fileNameAll
			// console.log(form)
			// 判断编辑时 时间按钮的状态
			form.isPermanents = form.isPermanent === 1
      isopendtime.value = form.timeValid === 1 ? true :false
      form.time_valids = isopendtime.value ? 1 : 0
      console.log(isopendtime.value)
			// 给禁用变量赋值
			if(form.isPermanents) {
				istimeswitch.value = true
			} else  {
        isopend.value = true
      }
			let originalUrl = `${actionUrl.value}/downloadFilec?id=${form.fileUid}`;
			let previewUrl  = originalUrl +  `&fullfilename=${form.fileUid}.${form.fileName}`
			//转换为 Base64 编码
			let base64EncodedUrl = btoa(previewUrl);
			//使用 encodeURIComponent 编码
			let encodedUrl = encodeURIComponent(base64EncodedUrl);
			allurl.value = actionUrl1.value + encodedUrl
		})
		.finally(() => {
			loading.value = false;
		});
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>
<style>
.el-form-item__content {
  margin-left: 0 !important;
}
.mr0 .el-form-item__content {

  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.el-dialog__footer {
	text-align: center !important;
}
.icon {
  width: 20px;
  height: 20px;
}

</style>
